
var map;


	  var hull;
      var markers = [];
      var markersRuta = [];
      var gpoly ;
      function initialize() {

     	gpoly = null;
        var properties = {
          center: new google.maps.LatLng(-12.0000, -77.0000),
          zoom: 11,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        
        map = new google.maps.Map(document.getElementById("map_canvas"),
            properties);
        
       
         
     	 google.maps.event.addListener(map, 'click', function(event) {
		    placeMarker(event.latLng);
		  });
      }
     
      function placeMarker(location) {
		  
		  var marker = new google.maps.Marker({
			  position: location,
			  map: map
		  });
		  google.maps.event.addListener(marker, 'click', function(event) {
			  
		  	  if ( markers.length != 0 ) {
		  	  	  var flag = false;
				  for( var i = 0; i < markers.length; i++){
				  	if (markers[ i ].position == location) {
				  		flag = true;
				  	}
				  	if ( flag ) {
						if ( i + 1 < markers.length ) markers[ i ] = markers[ i + 1 ];				  	
				  	}
				  }
				  markers.length = markers.length - 1;
			  }		    
			  marker.setMap( null );
			  hulling();
		  });
		  markers.push( marker );
		  
		  map.setCenter(location);
		  hulling();
	   }
	   function hulling(){
			if ( gpoly != null || markers.length < 3)
		   		gpoly.setMap(null);
			if ( markers.length < 3 ){
				return;	
			}						
			var poly = [];
			var points = new Array();
			for( var i = 0 ; i < markers.length ; i++){
				points[ i ] = new Point();
				points[ i ].setPoint( markers[i].position.lat(),  markers[i].position.lng()  );
			}

			hull = convexHull( points );

			
			
			for( var i = 0 ; i < hull.length ; i++){
				poly.push( new google.maps.LatLng( hull[i].x,  hull[i].y  ) );
			}
			var center = getCenterMass( hull );
		    var color =  $('#color').val(); 
		    
		  	gpoly = new google.maps.Polygon({
				paths: poly,
				strokeColor: color,
				strokeOpacity: 0.8,
				strokeWeight: 2,
				fillColor: color,
				fillOpacity: 0.35
		    });
		
		
			google.maps.event.addListener(gpoly, 'click', function(event) {
			    placeMarker(event.latLng);
			});
			
		    gpoly.setMap(map);
			map.setCenter( new google.maps.LatLng(center.x, center.y ));

	   }
      
	   function cleanPoints(){
		   for( var i = 0 ; i < markers.length ; i++){
			   markers[i].setMap(null);
		   }
		   markers.length = 0;
		   hulling();
		   
	   }
	   
	   function changeColor( txtbox ){
			hulling();
		   
	   }